package main

import (
	"boke/blogpb"
	"context"
	"fmt"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func (s *server) UpdateBlog(ctx context.Context, req *blogpb.UpdateBlogRequest) (*blogpb.UpdateBlogResponse, error) {
	fmt.Println("接收更新blog请求 Update blog request")

	blogreq := req.GetBlog()

	// 1. 查出对象
	blog_item := &blogItem{}
	err := db.Get(blog_item, select_sql, blogreq.Id)
	if err != nil {
		return nil, err
	}
	if blog_item.Title == "" {
		return nil, status.Errorf(
			codes.NotFound,
			fmt.Sprintf("没有查找到此博客 Cannot find blog with specified ID: %v", err),
		)
	}

	// 2. 更新数据
	blog_item.AuthorID = blogreq.AuthorId
	blog_item.Content = blogreq.Content
	blog_item.Title = blogreq.Title
	_, err = db.NamedExec(update_sql, blog_item)
	if err != nil {
		return nil, status.Errorf(
			codes.Internal,
			fmt.Sprintf("更新失败 Cannot update object in MongoDB: %v", err),
		)
	}

	return &blogpb.UpdateBlogResponse{
		Blog: &blogpb.Blog{
			Id:       blog_item.ID,
			AuthorId: blog_item.AuthorID,
			Content:  blog_item.Content,
			Title:    blog_item.Title,
		},
	}, nil
}
